package com.cn.wanxi.util;

import com.cn.wanxi.dao.impl.UserImpl;
import com.cn.wanxi.model.UserModel;

import java.sql.*;

/**
 * 手写一个JDBC
 * 1.下载驱动：加载驱动（什么时候加载？）
 * 2.得到连接  数据库连接
 * 3.编译sql语句
 * 4.执行sql语句
 * 5.返回值
 * 6.关闭连接
 */
public class JDBC {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

//    private static Connection connection = null;

    private JDBC() {
    }

    private static Connection getConnection() {
        Connection connection = null;
        try {
//            if (connection == null)
            String url = "jdbc:mysql://121.199.55.96:3306/canyin04";
            String user = "canyin04";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    public static void main(String[] args) {
//        String sql = "INSERT INTO `user` \n" +
//                "(`address`, `create_time`, `email`, `enable`, `password`, `phone`, `sex`, \n" +
//                "`update_time`, `username`, `hobby`, `birthday`)\n" +
//                " VALUES ('四川省成都市武侯区孵化园E座4楼', now(), 'fdsaafa@qq.com', '1', \n" +
//                " 'aaaaaa', '15284886666', '男', now(), 'wersdfs', '旅游,看书,游戏', now());";
//        System.out.println( update(sql));
//        String sql = "select * from user";
//        ResultSet query = query(sql);
//        System.out.println(query);
//        new UserImpl().findAll(null);
//        new UserImpl().findByUsernameAndPassword(null);
    }

    //得到连接：单例模式
//PreparedStatement 和Statement的区别？
    public static ResultSet query(String sql) {
        PreparedStatement preparedStatement = null;
        try {
//            编译sql语句
            preparedStatement = getConnection().prepareStatement(sql);
//            执行sql语句,并返回结果
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(String sql) {
        PreparedStatement preparedStatement = null;
        try {
//            编译sql语句
            preparedStatement = getConnection().prepareStatement(sql);
//            执行sql语句,并返回结果
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (preparedStatement != null)
                    preparedStatement.close();
//                System.out.println(1);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
}
